const Metalsmith = require('metalsmith');
const path = require('path');
const home = require('user-home');
const fse = require('fs-extra');
const Handlebars = require('handlebars');
const prompt = require('./e2e-prompt');
const filter = require('./e2e-filter');
const render = require('./e2e-replace');
const package = require('../package.json');


const templateVersion = package.version;

// register handlebars helper
Handlebars.registerHelper('if_eq', function (a, b, opts) {
    return a === b
        ? opts.fn(this)
        : opts.inverse(this)
});

Handlebars.registerHelper('unless_eq', function (a, b, opts) {
    return a === b
        ? opts.inverse(this)
        : opts.fn(this)
});


const opts = {
    helpers: {
        if_or(v1, v2, options) {
            if (v1 || v2) {
                return options.fn(this)
            }

            return options.inverse(this)
        },
        template_version() {
            return templateVersion
        },
    }
};

opts.helpers && Object.keys(opts.helpers).map(key => {
    Handlebars.registerHelper(key, opts.helpers[key])
});

let cache_template = path.join(home, '.vue-templates/webpack/template');

if (!fse.existsSync(cache_template)) {
    cache_template = path.join(__dirname, '../template');
}

const metalsmith = Metalsmith(cache_template);
const target = path.join(__dirname, '../target');

/**
 * 数据收集
 * 收集并挂载到metadata上,
 * 以便后面获取数据
 * @param {*} files 
 * @param {*} data 
 * @param {*} done 
 */
const dataCapture = (files, data, done) => {
    let flag = false;
    // let flag = true;
    if (flag) { // 本地模拟收集用户输入数据
        Object.assign(data, {
            isNotTest: true,
            name: 'simple-cli',
            description: 'A Vue.js project',
            author: 'LongXiaoBai <wlan945636373@gmail.com>',
            build: 'standalone',
            router: true,
            lint: false,
            unit: false,
            e2e: false,
            autoInstall: 'npm',
            templateVersion: '1.3.1'
        });
        done(); // 通过done()传递当前事件处理完毕的消息，通知下个插件可以开始工作，上个插件已处理完毕;
    } else {// 收集用户输入数据
        prompt(data, {}, done);
    }
}


// 1. 注入初始元数据
metalsmith.metadata({
    destDirName: 'simple-cli',
    inPlace: target === process.cwd(),
    noEscape: true
});

// 2. 收集并挂载数据
metalsmith.use((files, metalsmith, done) => {
    dataCapture(files, metalsmith.metadata(), done); // 需在powershell上运行
});

// 3. 过滤文件
metalsmith.use((files, metalsmith, done) => {
    filter(files, filters = [], metalsmith.metadata(), done);
});

// 4. 渲染模板
metalsmith.use((files, metalsmith, done) => {
    render(files, metalsmith.metadata(), done);
});

// 5.清空目标目录并向其拷贝注入文件
metalsmith.clean(true)
    .source('.') // 源目录
    .destination(target) // 模板目录
    .build((err, files) => {
        if (err) {
            console.log(`err is: ${err}`);
        } else {
            console.log(`complete success`);
        }
        // 拷贝注入完毕后, 进行npm install、eslint操作

        // if (typeof opts.complete === 'function') {
        //     const helpers = { chalk, logger, files }
        //     opts.complete(data, helpers)
        // } else {
        //     logMessage(opts.completeMessage, data)
        // }
    });